package cn.edu.service.impl;

import cn.edu.mapper.StockMapper;
import cn.edu.pojo.Stock;
import cn.edu.service.StockService;
import cn.edu.service.StockServiceLock;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author Mr.ma
 * @since 2022/12/8 16:09
 **/
@Service
public class StockServiceLockImpl implements StockServiceLock {
    @Resource
    private StockMapper stockMapper;
    @Override
    public String decrement(Integer id) {
        synchronized (StockServiceLockImpl.class.getClassLoader()) {
            Stock stock = stockMapper.selectById(id);
            if (stock != null) {
                if (stock.getStock() > 0) {
                    stock.setStock(stock.getStock() - 1);
                    stockMapper.updateById(stock);
                    System.out.println("修改库存数量成功，剩余库存为：" + stock.getStock());
                    return "修改库存数量成功，编号为" + id + "的商品剩余库存为：" + stock.getStock();
                }
            }
            System.out.println("编号为" + id + "的商品剩余库存不足");
            return "编号为" + id + "的商品剩余库存不足";
        }
    }
}
